# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/8/12
library(optparse)
library(magrittr)
library(impute)
library(tidyverse)

option_list <- list(
  make_option("--cc", default = "calculate_config.json", type = "character", help = "config file"),
  make_option("--si", default = "1;0", type = "character", help = "step")
)
opt <- parse_args(OptionParser(option_list = option_list))

args <- commandArgs(trailingOnly = F)
scriptPath <- dirname(sub("--file=", "", args[grep("--file", args)]))
source(str_c(scriptPath, "/base.R"))

configJson <- fromJSON(opt$cc)

si <- opt$si %>%
  str_split(";") %>%
  unlist()
step <- si[1] %>%
  as.numeric()
mergeMethod <- configJson$datas$mergeMethod[step]
mergeMethod

data <- read_tsv(str_c(step - 1, ".result.txt")) %>%
  rename(Metabolite = 1)

outData <- data %>%
  mutate_at(vars(c("Metabolite")), function(x) {
    str_replace(x, "_\\d+$", "")
  }) %>%
  mutate(Metabolite = factor(Metabolite, levels = unique(Metabolite))) %>%
  group_by(Metabolite)

outData <- if (mergeMethod == "sum") {
  outData %>%
    summarise_all(sum)
}else if (mergeMethod == "mean") {
  outData %>%
    summarise_all(mean)
}else {
  outData %>%
    summarise_all(median)
}

outData

write_tsv(outData, str_c(step, ".result.txt"))
write_csv(outData, str_c(step, ".var_merge.csv"))








